﻿package com.wicture.erp4android.ui;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.okhttp.Request;
import com.wicture.erp4android.R;
import com.wicture.erp4android.net.OkHttpClientManager;
import com.wicture.erp4android.net.ServerUrl;
import com.wicture.erp4android.utils.LogUtil;

/**
 * 欢迎界面
 * @author Administrator
 *
 */
public class WelcomeAct extends Activity {

	private String versionFromServer;
	private String currentVersion;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_welcome);
		initData();
		SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
		if(!update()){
		final String user = sp.getString("user", null);
			new Handler().postDelayed(new Runnable() {
				public void run() {
					if(user!=null){
						
						toMain();
					}else{
					toLogin();
					}
				}
			}, 3000);
			
		}
			
			
		}
	private boolean update() {
		currentVersion = getVersionName();
		HttpUtils httpUtils = new HttpUtils(1000);
		httpUtils.send(HttpMethod.GET, "", new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				versionFromServer = responseInfo.result;
				
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				// TODO Auto-generated method stub
				
			}
		});
		if(currentVersion.equals(versionFromServer)){
			chooseUpdate();
			return true;
		}else{
			return false;
		}
		
	}
	/**
	 * 下载新版本并安装
	 */
	private void download() {
		// TODO Auto-generated method stub
		final String fileName = "ERP4Android"+versionFromServer;
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.download("", fileName, new RequestCallBack<File>() {
			
			@Override
			public void onSuccess(ResponseInfo<File> responseInfo) {
				// TODO Auto-generated method stub
				install(fileName);
			}
			
			@Override
			public void onFailure(HttpException error, String msg) {
				// TODO Auto-generated method stub
				
			}
		});
		
	}
	/**
	 * 加载数据
	 */
	private void initData() {
		// TODO Auto-generated method stub
//		OkHttpClientManager.getAsyn(ServerUrl.WINTINGURL, new OkHttpClientManager.ResultCallback<String>() {
//			
//			@Override
//			public void onError(Request request, Exception e) {
//				// TODO Auto-generated method stub
//				
//			}
//
//			@Override
//			public void onResponse(String response) {
//				// TODO Auto-generated method stub
//				
//			}
//			@Override
//			public void onBefore(Request request) {
//				// TODO Auto-generated method stub
//				super.onBefore(request);
//			}
//			@Override
//			public void onAfter() {
//				// TODO Auto-generated method stub
//				super.onAfter();
//			}
//			
//		});
		HttpUtils http = new HttpUtils(2000);
		http.send(HttpMethod.GET,ServerUrl.WINTINGURL,new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				// TODO Auto-generated method stub
				LogUtil.e("WelcomeAct","wuchangzhong");
				System.out.println(responseInfo.result);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				// TODO Auto-generated method stub
				//System.out.println("123");
			}
			
		});
		
	}
	protected void toLogin() {
		Intent intent = new Intent(this, LoginAct.class);
		startActivity(intent);
		finish();
	}
	private void toMain(){
		Intent intent = new Intent(this, MainAct.class);
		startActivity(intent);
		finish();
	}
	
	/**
	 * 更新版本
	 */
	private void upDate(){
		String version = getVersion();
		getDataFromNet();
	}
	private void getDataFromNet() {
		// TODO Auto-generated method stub
		
	}
	/**
	 * 获取版本名
	 * @return
	 */
	private String getVersion() {
		PackageManager packageManager = getPackageManager();
		try {
			// 2.根据包名获取应用程序相关信息
			// packageName : 应用程序的包名
			// flags ： 指定信息的标签，指定了标签就会获取相应标签对应的相关信息
			// PackageManager.GET_ACTIVITIES : 获取跟activity相关的信息
			// getPackageName() : 获取应用程序的包名
			PackageInfo packageInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			// 3.获取应用程序版本号名称
			String versionName = packageInfo.versionName;
			LogUtil.i("版本名", versionName);
			return versionName;
		} catch (NameNotFoundException e) {
			// 找不到包名的异常
			e.printStackTrace();
			return null;
		}
	// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		toLogin();
	}
	
	protected void install(String fileName) {
		/**
		 * <intent-filter> <action android:name="android.intent.action.VIEW" />
		 * <category android:name="android.intent.category.DEFAULT" /> <data
		 * android:scheme="content" />// content:// <data android:scheme="file"
		 * />// file:代表文件 File <data
		 * android:mimeType="application/vnd.android.package-archive" />
		 * </intent-filter>
		 */
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");

		// setData和setType是相互冲突的，两个数据是会相互覆盖的
		// intent.setType("application/vnd.android.package-archive");
		// intent.setData(Uri.fromFile(new
		// File("/mnt/sdcard/mobilesafexian2.0.apk")));
		// file:///:调用本地的文件
		intent.setDataAndType(
				Uri.fromFile(new File(fileName)),
				"application/vnd.android.package-archive");

		// 在当前的activity退出的时候，会调用之前activity的OnActivityResult方法
		// requestCode : 请求码,表示activity去打开新的activity的时候在新的activity中标示
		startActivityForResult(intent, 0);

	}
	public String getVersionName() {
		// 1.包的管理者，获取应用程序中清单文件中信息
		PackageManager packageManager = getPackageManager();
		try {
			// 2.根据包名获取应用程序相关信息
			// packageName : 应用程序的包名
			// flags ： 指定信息的标签，指定了标签就会获取相应标签对应的相关信息
			// PackageManager.GET_ACTIVITIES : 获取跟activity相关的信息
			// getPackageName() : 获取应用程序的包名
			PackageInfo packageInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			// 3.获取应用程序版本号名称
			String versionName = packageInfo.versionName;
			LogUtil.i("版本名", versionName);
			return versionName;
		} catch (NameNotFoundException e) {
			// 找不到包名的异常
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 选择是否下载新版本
	 */
	private void chooseUpdate(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("检测到新版本");
		builder.setMessage("点击确定更新");
		builder.setPositiveButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				download();
				
			}
		});
		builder.create();
		builder.show();
	}
}